import React, {
  PropsWithChildren,
  useCallback,
  useEffect,
  useState,
} from 'react';
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { CategoryItemType, CategoryRespType } from '@/types/category';
import Skeleton from '@/components/Skeleton';
import { getJsonFile } from '@/utils/sts';

import './index.module.scss';

const IndexPage: React.FC<PropsWithChildren> = () => {
  const [rootCategory, setRootCategory] = useState<CategoryRespType | null>(
    null
  );
  const [loading, setLoading] = useState(true);

  const handleJump = useCallback((data: CategoryItemType) => {
    if (data.hasChildren) {
      Taro.navigateTo({ url: `/pages/category/index?id=${data.id}` });
    } else {
      Taro.navigateTo({ url: `/pages/product/index?id=${data.id}` });
    }
  }, []);

  const getRootCategory = useCallback(async () => {
    setLoading(true);
    const data = await getJsonFile<CategoryRespType>('category/root.json');
    if (!data) {
      Taro.showToast({ title: '获取数据失败', icon: 'none' });
      return;
    }
    setRootCategory(data);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
  }, []);

  useEffect(() => {
    getRootCategory();
  }, []);

  return (
    <React.Fragment>
      {loading ? (
        <Skeleton />
      ) : (
        <View className='container'>
          <View className='company-img'></View>
          <View className='show-text'>产品展示</View>
          <View className='category-list'>
            {rootCategory?.children.map(item => (
              <View
                key={item.id}
                className='category-item'
                onClick={() => handleJump(item)}
              >
                {item.name}
              </View>
            ))}
          </View>
        </View>
      )}
    </React.Fragment>
  );
};

export default IndexPage;
